package org.grayrabbit.cloud.core.config;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathException;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.lang.StringUtils;
import org.xml.sax.InputSource;

public class SimpleXmlConfigurator extends Configurator {
	private String file;
	private String root;

	public SimpleXmlConfigurator(String file) {
		this.file = file;
		this.root = "string(/configuration/";
	}

	public SimpleXmlConfigurator(String file, String root) {
		this.file = file;
		this.root = ("string(/" + root + "/");
	}

	private String op(String exp) throws ConfiguratorException {
		try {
			XPath path = XPathFactory.newInstance().newXPath();
			String value = (String) path.evaluate(exp, readInputSource(file), XPathConstants.STRING);
			if (StringUtils.isBlank(value))
				return null;
			return value.trim();
		} catch (XPathException e) {
			throw new ConfiguratorException(e);
		}		  

	}
	private InputSource readInputSource(String file){
		assert(StringUtils.isNotBlank(file));
		if(file.startsWith("classpath:")){
			String uri = file.substring(10);
			return new InputSource(SimpleXmlConfigurator.class.getResourceAsStream(uri));
		}else{
			return new InputSource(file);
		}
			
	}
	protected String read(String category, String name, String property)
			throws ConfiguratorException {
		String path = this.root + category;
		if (name != null)
			path = path + "s/" + category
					+ String.format("[@name=\"%s\"]/", new Object[] { name });
		else {
			path = path + "/";
		}
		path = path + "@" + property + ")";
		return op(path);
	}

}
